<?php

namespace App\Library\Express;

use Exception;

class ExpressApi extends BaseExpressApi
{
    /**
     * 查询物流
     *
     * @param string $companyCode
     * @param string $expressNo
     * @param string $phone
     * @return array
     * @throws Exception
     */
    public function query(string $companyCode, string $expressNo, string $phone = ''): array
    {
        //参数设置
        $param = array(
            'com' => $companyCode,             // 快递公司编码
            'num' => $expressNo,     // 快递单号
        );

        if (!empty($phone)) {
            $param['phone'] = $phone;
        }

        //请求参数
        $postData = [
            'customer' => $this->customer,
            'param' => json_encode($param, JSON_UNESCAPED_UNICODE),
        ];
        $postData['sign'] = $this->makeSign($postData);

        $result = $this->curlPost(self::QUERY_URL, $postData);
        if (!empty($result['returnCode']) && $result['returnCode'] == 500) {
            return [];
        }
        if (isset($result['returnCode']) && $result['returnCode'] !== 200) {
            throw new Exception($result['message']);
        }

        return $result['data'];
    }

    /**
     * 生成签名
     * @param array $params
     * @return string
     */
    protected function makeSign(array $params): string
    {
        return strtoupper(md5($params['param'] . $this->key . $params['customer']));
    }

    public function curlPost(string $url, array $params = [], bool $origin = false)
    {
        // 发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }
}
